package com.maoye.ossp.biz.statement.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.maoye.ossp.biz.statement.entity.StatementOrder;
import com.maoye.ossp.biz.statement.entity.StatementOrderDetail;
import com.maoye.ossp.biz.statement.service.StatementOrderDetailService;
import com.maoye.ossp.biz.statement.service.StatementOrderService;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.ossp.webserviceClient.PosPayWebService;

/**
 * 订单controller类
 * 
 * @author yanghao
 * 
 */
@Controller
@RequestMapping(value = "biz/statement/statementOrder/")
public class StatementOrderController extends BaseController {

	@Resource
	private StatementOrderService statementOrderService;

	@Resource
	private StatementOrderDetailService statementOrderDetailService;
	
	@Resource
	private ISupplierService supplierService;
	

	/**
	 * 展示订单列表信息
	 * 
	 * @param statementOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author tf
	 * @data 2014年3月18日
	 */
	@RequestMapping(value = "list")
	public String list(StatementOrder statementOrder,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		//用来判断是  订单还是 调价单
		String flag=request.getParameter("flag");
		//获取登陆用户Id 
		Long userId=UserUtils.getCurrentUserId();
		//根据当前用户Id 如果是供应商 获取用户获取供应商信息
		Supplier supplier=supplierService.get(userId);
		QueryFilter queryFilter = getQuerFilter(request, statementOrder);	
		//设置供应商编码
		if(supplier!=null){
			queryFilter.addFilter("supplierNo", supplier.getSupplierNo(), QueryOP.EQUAL);
		 }
		if(flag!=null){
			queryFilter.addFilter("flag",flag, QueryOP.EQUAL);
		}
		Page<StatementOrder> page = (Page<StatementOrder>) statementOrderService
				.find(queryFilter);
		model.addAttribute("page", page);
		model.addAttribute("statementOrder", statementOrder);
		return resultPage("/biz/statement/statementOrder/list", model, request);
	}

	/**
	 * 展示订单详细信息
	 * 
	 * @param statementOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "view")
	public String view(StatementOrder statementOrder,
			StatementOrderDetail statementOrderDetail,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String id = statementOrder.getId().toString();
		StatementOrder order = statementOrderService.get(id);
		String orderNo = request.getParameter("orderNo");
		QueryFilter queryFilter = getQuerFilter(request, statementOrderDetail);
		queryFilter.getParams().put("billNo", orderNo);
		Page<StatementOrderDetail> page = (Page<StatementOrderDetail>) statementOrderDetailService
				.find(queryFilter);
		StatementOrderDetail varOrderDetail = new StatementOrderDetail();
		String total = "合计";
		double quantity = 0;
		double totalMoney = 0;
		/*
		 * String param="{promNo:"; param=param+prom.getPromNo()+"}";
		 * JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		 * factory.setServiceClass(PosPayWebService.class); factory.setAddress(
		 * "http://202.105.115.147:9000/ossp-web/service/pospayWebService");
		 * PosPayWebService service = (PosPayWebService) factory.create();
		 * String result = service.queryByQueryFilter(param);
		 */
		List<StatementOrderDetail> list = page.getList();
		if (list != null) {
			for (StatementOrderDetail orderDetail : list) {
				/*JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
				factory.setServiceClass(PosPayWebService.class);
				factory.setAddress("http://202.105.115.147:9000/ossp-web/service/pospayWebService");
				PosPayWebService service = (PosPayWebService) factory.create();
				String result = service.getGoodsInfo(orderDetail.getBarCode(),
						orderDetail.getGoodsCode());
				Gson gson = new Gson();
				JSONObject a = new JSONObject(result);
				Object b = a.get("data");
				JSONArray array = new JSONArray(b.toString());
				for (int i = 0; i < array.length(); i++) {
					JSONObject json = (JSONObject) array.get(i);
					orderDetail.setMantr(String.valueOf(json.get("goodscode"))
							.substring(10, 18));
					orderDetail.setBarCode(String.valueOf(json.get("barcode")));
					orderDetail.setGoodsName(String.valueOf(json
							.get("goodsname")));
					orderDetail.setModelNumber(String.valueOf(json
							.get("goodsModel")));
				}*/
				quantity = quantity + orderDetail.getQuantity();
				totalMoney = totalMoney + orderDetail.getAmount();
			}
		}
		varOrderDetail.setMantr(total);
		varOrderDetail.setQuantity(quantity);
		varOrderDetail.setAmount(totalMoney);
		page.getList().add(varOrderDetail);
		model.addAttribute("listSize", page.getList().size());
		model.addAttribute("page", page);
		model.addAttribute("statementOrder", order);
		return "/biz/statement/statementOrder/view";
	}

	/**
	 * 导出订单详细信息
	 * 
	 * @param statementOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "ExportDetailToExcel")
	public void ExportDetailToExcel(StatementOrder statementOrder,
			StatementOrderDetail statementOrderDetail,
			HttpServletRequest request, HttpServletResponse response) {
		String id = statementOrder.getId().toString();
		StatementOrder order = statementOrderService.get(id);
		if (order.getOrderStatus().equals("1")) {
			order.setOrderStatus("有效");
		} else {
			order.setOrderStatus("无效");
		}
		if (order.getOrderType().equals("ZN01")) {
			order.setOrderType("经销采购订单");
		} else if (order.getOrderType().equals("ZN02")) {
			order.setOrderType("代销采购订单");
		} else if (order.getOrderType().equals("ZN11")) {
			order.setOrderType("经销直配订单");
		} else if (order.getOrderType().equals("ZN12")) {
			order.setOrderType("代销直配订单");
		} else if (order.getOrderType().equals("ZR01")) {
			order.setOrderType("商品退货订单");
		} else if (order.getOrderType().equals("ZR02")) {
			order.setOrderType("代销商品退货订单");
		} else if (order.getOrderType().equals("ZR03")) {
			order.setOrderType("经销直配退货订单");
		} else if (order.getOrderType().equals("ZR04")) {
			order.setOrderType("代销直配退货订单");
		} else if (order.getOrderType().equals("ZTZ1")) {
			order.setOrderType("仓库成本调整订单");
		} else if (order.getOrderType().equals("ZTZ2")) {
			order.setOrderType("门店成本调整订单");
		}
		String orderNo = request.getParameter("orderNo");
		QueryFilter queryFilter = getQuerFilter(request, statementOrderDetail);
		queryFilter.getParams().put("billNo", orderNo);
		Page<StatementOrderDetail> page = (Page<StatementOrderDetail>) statementOrderDetailService
				.find(queryFilter);
		StatementOrderDetail varOrderDetail = new StatementOrderDetail();
		String total = "合计";
		double quantity = 0;
		double totalMoney = 0;
		List<StatementOrderDetail> list = page.getList();
		if (list != null) {
			for (StatementOrderDetail orderDetail : list) {
				JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
				factory.setServiceClass(PosPayWebService.class);
				factory.setAddress("http://202.105.115.147:9000/ossp-web/service/pospayWebService");
				PosPayWebService service = (PosPayWebService) factory.create();
				String result = service.getGoodsInfo(orderDetail.getBarCode(),
						orderDetail.getGoodsCode());
				Gson gson = new Gson();
				JSONObject a = new JSONObject(result);
				Object b = a.get("data");
				JSONArray array = new JSONArray(b.toString());
				for (int i = 0; i < array.length(); i++) {
					JSONObject json = (JSONObject) array.get(i);
					orderDetail.setMantr(String.valueOf(json.get("goodscode"))
							.substring(10, 18));
					orderDetail.setBarCode(String.valueOf(json.get("barcode")));
					orderDetail.setGoodsName(String.valueOf(json
							.get("goodsname")));
					orderDetail.setModelNumber(String.valueOf(json
							.get("goodsModel")));
				}
				quantity = quantity + orderDetail.getQuantity();
				totalMoney = totalMoney + orderDetail.getAmount();
			}
		}
		/*
		 * BigDecimal bg = new BigDecimal(1234.456789); double j =
		 * bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		 * 
		 * double g=bg.setScale(-1, BigDecimal.ROUND_HALF_UP).doubleValue();
		 */
		varOrderDetail.setMantr(total);
		varOrderDetail.setQuantity(quantity);
		varOrderDetail.setAmount(totalMoney);
		page.getList().add(varOrderDetail);

		try {
			// 设置输出的格式
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			// 获取浏览器类型
			String user_agent = request.getHeader("User-Agent").toLowerCase();
			String fileName = "";
			// 为不同的浏览器，对文件名进行不同的编码转换
			if (user_agent.indexOf("firefox") > 0) {
				fileName = new String("订单明细".getBytes("UTF-8"), "iso8859-1");
			} else {
				fileName = URLEncoder.encode("订单明细", "UTF-8");
			}
			response.setHeader("Content-disposition", "attachment; filename="
					+ fileName + ".xls");
			OutputStream os = response.getOutputStream();
			statementOrderService
					.ExportDetailToExcel(order, page.getList(), os);
			response.flushBuffer();
		} catch (IOException ex) {
			System.out.println("导出数据出错");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * 打印订单信息信息
	 * 
	 * @param statementOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author tf
	 * @data 2014年3月18日
	 */
	@RequestMapping(value = "print")
	public String print(StatementOrder statementOrder,
			StatementOrderDetail statementOrderDetail,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String id = statementOrder.getId().toString();
		StatementOrder order = statementOrderService.get(id);
		String orderNo = request.getParameter("orderNo");
		QueryFilter queryFilter = getQuerFilter(request, statementOrderDetail);
		queryFilter.getParams().put("billNo", orderNo);
		Page<StatementOrderDetail> page = (Page<StatementOrderDetail>) statementOrderDetailService
				.find(queryFilter);
		StatementOrderDetail varOrderDetail = new StatementOrderDetail();
		String total = "合计";
		double quantity = 0;
		double totalMoney = 0;
		for (StatementOrderDetail orderDetail : page.getList()) {
			quantity = quantity + orderDetail.getQuantity();
			totalMoney = totalMoney + orderDetail.getAmount();
		}
		varOrderDetail.setMantr(total);
		varOrderDetail.setQuantity(quantity);
		varOrderDetail.setAmount(totalMoney);
		page.getList().add(varOrderDetail);
		List<StatementOrderDetail> list = page.getList();
		model.addAttribute("listSize", page.getList().size());
		model.addAttribute("list", list);
		model.addAttribute("statementOrder", order);
		return "/biz/statement/statementOrder/print";
	}

	public StatementOrderService getStatementOrderService() {
		return statementOrderService;
	}

	public void setStatementOrderService(
			StatementOrderService statementOrderService) {
		this.statementOrderService = statementOrderService;
	}

}
